package net.ak.controller;

import java.util.Date;

import net.ak.constant.Constant;
import net.ak.model.User;
import net.ak.model.UserMaster;
import net.ak.response.AKResponse;
import net.ak.service.UserMasterService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api/um")
public class UserMasterController {

	@Autowired
	private UserMasterService userMasterService;
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody AKResponse addUserMaster(@RequestParam String browser, @RequestParam String ip, @RequestParam Long date, @RequestParam Long userId) {
		User user 				= new User();
		user.setId(userId);
		//--- Create UserMaster ---//
		UserMaster master 		= new UserMaster();
		master.setBrowser(browser);
		master.setCreatedDate(new Date(date));
		master.setIp(ip);
		master.setUser(user);
		boolean result 			= userMasterService.saveOrUpdate(master);
		
		AKResponse akResponse 	= new AKResponse();
		akResponse.setStatusCode(result 	? Constant.SUCCESS_CODE 	: Constant.INSERT_ERROR_CODE);
		akResponse.setStatusMessage(result 	? Constant.SUCCESS_MESSAGE 	: Constant.INSERT_ERROR_MESSAGE);
		akResponse.setResponseData(result 	? master : null);
		
		return akResponse;
	}
	
	@RequestMapping(value = "/listall", method = RequestMethod.POST)
	public @ResponseBody AKResponse listAllUserMasters() {
		AKResponse akResponseSuccess = new AKResponse(Constant.SUCCESS_CODE, Constant.SUCCESS_MESSAGE);
		akResponseSuccess.setResponseData(userMasterService.listUserMaster());
		
		return akResponseSuccess;
	}
	
	@RequestMapping(value = "/listbyuser")
	public @ResponseBody AKResponse listAllUserMastersByUser(@RequestParam long userId) {
		User user 				= new User();
		user.setId(userId);
		AKResponse akResponseSuccess = new AKResponse(Constant.SUCCESS_CODE, Constant.SUCCESS_MESSAGE);
		akResponseSuccess.setResponseData(userMasterService.listUserMasterByUser(user));
		
		return akResponseSuccess;
	}
	
	@RequestMapping(value = "/listbyip")
	public @ResponseBody AKResponse listAllUserMastersByUser(@RequestParam String ip) {
		AKResponse akResponseSuccess = new AKResponse(Constant.SUCCESS_CODE, Constant.SUCCESS_MESSAGE);
		akResponseSuccess.setResponseData(userMasterService.listUserMasterByIP(ip));
		
		return akResponseSuccess;
	}
	
	@RequestMapping(value = "/listbybrowser")
	public @ResponseBody AKResponse listAllUserMastersByBrowser(@RequestParam String browser) {
		AKResponse akResponseSuccess = new AKResponse(Constant.SUCCESS_CODE, Constant.SUCCESS_MESSAGE);
		akResponseSuccess.setResponseData(userMasterService.listUserMasterByBrowser(browser));
		
		return akResponseSuccess;
	}
}
